package m.base.util;

import m.app.service.AppLoginService;
import m.appserver.AuthInfoUtil;
import m.base.model.StoreInfo;
import m.base.model.UserInfo;
import m.common.model.util.ModelQueryList;
import m.store.model.GuestInfo;
import m.store.model.RepositoryInfo;
import m.system.RuntimeData;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.StringUtil;
import manage.model.AdminLogin;
import manage.model.OrgGroupView;
import manage.model.StatusModel;
import manage.service.AdminGroupPowerService;

import java.util.Date;
import java.util.List;

public class PowerUtil {
    /**
     * 管理员权限 系统
     */
    public final static String SysData="base_data_power";
    /**
     * 库存管理权限 业务
     */
    public final static String Stock="stock_data_power";
    /**
     * 财务管理权限 业务
     */
    public final static String Finance="finance_data_power";
    /**
     * 商户管理权限 业务
     */
    public final static String Store="store_data_power";
    /**
     * 统计汇总 业务
     */
    public final static String Collect="collect_data_power";
    private static final ThreadLocal<String> appSession = new ThreadLocal<>();
    public static void setAppKey(String key){
        appSession.set(key);
    }

    public static void setAppUser(String key,String userOid){
        CacheUtil.pushLocal(key, userOid);
    }
    public static void clearAppUser(String key){
        CacheUtil.clear(key);
    }
    /**
     * 获取当前登录用户
     */
    public static UserInfo getSessionUser() throws Exception {
        AdminLogin admin=AuthInfoUtil.getSessionAdmin();
        if(null!=admin) return CacheUtil.get(UserInfo.class,admin.getOid());
        String as=appSession.get();
        if(StringUtil.notSpace(as)){
            Object userOid=CacheUtil.getLocal(as);
            if(null==userOid){
                UserInfo user=RuntimeData.getService(AppLoginService.class).getUser(as);
                if (null != user) {
                    return CacheUtil.get(UserInfo.class,user.getOid());
                }
            }else{
                return CacheUtil.get(UserInfo.class,(String)userOid);
            }
        }
        return null;
    }
    /**
     * 获取当前登录用户
     */
    public static UserInfo getSessionUser(boolean isThrow) throws Exception {
        UserInfo user=getSessionUser();
        if(isThrow&&null==user) throw AuthInfoUtil.noPowerException;
        if(null!=user&&StatusModel.Status_Disabled.equals(user.getStatus())) throw new MException(PowerUtil.class,"用户已停用，请联系商家管理员。");
        return user;
    }
    /**
     * 获取当前登录用户oid
     */
    public static String getSessionUserOid() throws Exception {
        return getSessionUser(true).getOid();
    }
    /**
     * 获取当前登录用户商户
     */
    public static StoreInfo getSessionStore() throws Exception {
        OrgGroupView org=getSessionUser(true).getOrgGroup();
        if(null==org) return null;
        return CacheUtil.get(StoreInfo.class,org.getOid());
    }
    /**
     * 获取当前登录用户商户
     */
    public static StoreInfo getSessionStore(boolean isThrow) throws Exception {
        StoreInfo store=getSessionStore();
        if(isThrow&&null==store) throw AuthInfoUtil.noPowerException;
        return store;
    }
    /**
     * 获取当前登录用户商户oid
     */
    public static String getSessionStoreOid() throws Exception {
        return getSessionStore(true).getOid();
    }
    /**
     * 验证操作权限
     *  power 在module.xml配置文件中配置  如果传入多个, 有一个满足即可
     */
    public static UserInfo verifyPower(String... power) throws Exception{
        UserInfo login=getSessionUser(true);
        if(power.length==0||power.length==1&&StringUtil.isSpace(power[0])) throw AuthInfoUtil.noPowerException;
        OrgGroupView org=getSessionStore();
        if(RuntimeData.getService(AdminGroupPowerService.class).hasPower(login.getOid(),null!=org?org.getOid():"", power)){
            return login;
        }else{
            throw AuthInfoUtil.noPowerException;
        }
    }
    /**
     * 判断是否有操作权限  如果传入多个, 有一个满足即可
     */
    public static boolean hasPower(String... power) throws Exception {
        UserInfo login=getSessionUser(true);
        if(power.length==0||power.length==1&&StringUtil.isSpace(power[0])) return false;
        OrgGroupView org=getSessionStore();
        return RuntimeData.getService(AdminGroupPowerService.class).hasPower(login.getOid(),null!=org?org.getOid():"", power);
    }
    /**
     * 验证是否当前登录商户
     */
    public static void verifyStoreData(String storeOid) throws Exception {
        if(!storeOid.equals(getSessionStoreOid())) throw AuthInfoUtil.noPowerException;
    }
    /**
     * 验证是否当前登录用户
     */
    public static void verifyUserData(String userOid) throws Exception {
        if(!userOid.equals(getSessionUserOid())) throw AuthInfoUtil.noPowerException;
    }

    /**
     * 获取自己客户信息
     */
    public static GuestInfo getSelfGuestInfo() throws Exception {
        return ModelQueryList.getModel(GuestInfo.class,getSessionStoreOid(),"*");
    }

    /**
     * 获取商户默认仓库
     */
    public static RepositoryInfo getDefRepository() throws Exception {
        List<RepositoryInfo> ls=CacheUtil.getList(RepositoryInfo.class,getSessionStoreOid());
        for(RepositoryInfo re : ls){
            if(RepositoryInfo.Yes.equals(re.getDefRepository())){
                return re;
            }
        }
        return new RepositoryInfo();
    }

    private static final String VerifyAccountDateFormat="yyyy年MM月";
    /**
     * 验证时间是否逾期
     */
    public static void verifyAccountDate(Date date,String dateName) throws Exception {
        Date d=new Date();
        int day=Integer.parseInt(DateUtil.format(d,"dd"));
        int set=Integer.parseInt(getSessionStore(true).getAccountDay());
        String dateString=DateUtil.format(date,VerifyAccountDateFormat);
        if(day>=set){//账期结束日及以后
            String now=DateUtil.format(d,VerifyAccountDateFormat);
            if(!now.equals(dateString)){
                throw new MException(PowerUtil.class,dateName+"跨账期，请选择"+now+"的日期。");
            }
        }else{//账期结束日之前
            String now1=DateUtil.format(DateUtil.getLastMonth(d),VerifyAccountDateFormat);
            String now2=DateUtil.format(d,VerifyAccountDateFormat);
            if(!(now1.equals(dateString)||now2.equals(dateString))){
                throw new MException(PowerUtil.class,dateName+"跨账期，请选择"+now1+"或"+now2+"的日期。");
            }
        }
    }

    /**
     * 返回当前商户是否需要仓库审核
     */
    public static boolean isRepositoryCheck() throws Exception {
        return StringUtil.noSpace(getSessionStore(true).getRepositoryCheck()).equals("Y");
    }
}
